from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import desc, func
from src.database import get_db
from src.models import User, Favorite, Spot, Order
from src.schemas.users import ChangePasswordRequest, FavoriteSpotResponse
from src.auth import get_current_user
from src.utils.security import verify_password, get_password_hash

router = APIRouter()

@router.post("/change-password")
def change_password(
    request: ChangePasswordRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    # 验证原密码
    if not verify_password(request.old_password, current_user.password):
        raise HTTPException(status_code=400, detail="原密码不正确")
    
    # 更新密码
    current_user.password = get_password_hash(request.new_password)
    db.commit()
    
    return {"message": "密码修改成功"}

@router.get("/favorites", response_model=list[FavoriteSpotResponse])
async def get_favorites(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户收藏的景点列表"""
    favorites = (
        db.query(Favorite)
        .filter(Favorite.user_id == current_user.id)
        .join(Favorite.spot)
        .order_by(desc(Favorite.created_at))
        .all()
    )
    
    return [
        FavoriteSpotResponse(
            id=fav.spot.id,
            name=fav.spot.name,
            description=fav.spot.description,
            price=fav.spot.price,
            images=fav.spot.images,
            favorited_at=fav.created_at
        )
        for fav in favorites
    ]

@router.post("/favorites/{spot_id}")
def add_favorite(
    spot_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """添加收藏"""
    # 检查景点是否存在
    spot = db.query(Spot).filter(Spot.id == spot_id).first()
    if not spot:
        raise HTTPException(status_code=404, detail="景点不存在")
    
    # 检查是否已经收藏
    existing = (
        db.query(Favorite)
        .filter(
            Favorite.user_id == current_user.id,
            Favorite.spot_id == spot_id
        )
        .first()
    )
    if existing:
        raise HTTPException(status_code=400, detail="已经收藏过该景点")
    
    # 创建收藏
    favorite = Favorite(user_id=current_user.id, spot_id=spot_id)
    db.add(favorite)
    db.commit()
    
    return {"message": "收藏成功"}

@router.delete("/favorites/{spot_id}")
def remove_favorite(
    spot_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消收藏"""
    favorite = (
        db.query(Favorite)
        .filter(
            Favorite.user_id == current_user.id,
            Favorite.spot_id == spot_id
        )
        .first()
    )
    
    if not favorite:
        raise HTTPException(status_code=404, detail="未找到该收藏")
    
    db.delete(favorite)
    db.commit()
    
    return {"message": "取消收藏成功"}

@router.get("/order-summary")
async def get_order_summary(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户订单统计信息"""
    stats = (
        db.query(
            func.count(Order.id).label('total_orders'),
            func.sum(Order.total_price).label('total_spent')
        )
        .filter(Order.user_id == current_user.id)
        .first()
    )

    recent_orders = (
        db.query(Order)
        .filter(Order.user_id == current_user.id)
        .join(Order.spot)
        .order_by(desc(Order.visit_date))
        .limit(5)
        .all()
    )

    return {
        "total_orders": stats[0] or 0,
        "total_spent": float(stats[1] or 0),
        "recent_spots": [order.spot.name for order in recent_orders]
    } 